package com.lixueju.security.box.resource;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lixueju.security.box.core.dto.ResultData;
import com.lixueju.security.box.core.enums.ResultDataEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lixueju
 * @since 2019/11/12 9:42
 **/
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResultData resultData = null;
        Throwable cause = authException.getCause();
        if (cause instanceof InvalidTokenException) {
            resultData = new ResultData(ResultDataEnum.AUTH_INVALID_TOKEN.code(), ResultDataEnum.AUTH_INVALID_TOKEN.desc(), null);
        } else {
            resultData = new ResultData(ResultDataEnum.AUTH_NONE_TOKEN.code(), ResultDataEnum.AUTH_NONE_TOKEN.desc(), null);
        }
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), resultData);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}
